#!/usr/bin/env python
# ._*_.conding:utf-8._*_

from flask import jsonify
from flask import g, request, current_app
from flask import jsonify,request,current_app
from flask import g, session
from ihome.utils.common import get_user_info
from ihome.utils.response_code import RET
from ihome.models import User, House
from . import register_login_bp
from . import api,get_user_info
from ihome.utils.pic_store import pic_store
from ihome import constants
from ihome import db


@register_login_bp.route("/user")
@get_user_info
def get_login_user():
    """获取登录用户信息 后端接口"""
    login_user = g.user
    user_obj = login_user.to_dict() if login_user else None
    data = {
        "avatar_url": user_obj.get("avatar_url"),
        "mobile": user_obj.get("mobile"),
        "name": user_obj.get("name")
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@api.route("/user/auth", methods=['POST', 'GET'])
@get_user_info
def set_real_user():
    """获取&设置用户实名认证信息 后端接口"""
    login_user = g.user
    if request.method == "GET":
        if not login_user:
            return jsonify(errno=RET.NODATA, errmsg="用户不存在")
        auth_dict = login_user.to_auth_info()
        data = {
            "real_name": auth_dict.get("real_name"),
            "id_card": auth_dict.get("id_card")
        }
        return jsonify(errno=RET.OK, errmsg="OK", data=data)

    else:
        # 设置用户实名认证信息 后端接口
        real_name = request.json.get("real_name")
        id_card = request.json.get("id_card")
        if not all([real_name, id_card]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

        login_user.real_name = real_name
        login_user.id_card = id_card
        try:
            db.session.commit()
        except Exception as err:
            db.session.rollback()
            current_app.logger.error(err)
            return jsonify(errno=RET.DBERR, errmsg="数据库修改实名认证信息异常")

        return jsonify(errno=RET.OK, errmsg="实名认证成功")


@register_login_bp.route("/user/houses")
@get_user_info
def get_user_houses():
    """获取当前登录用户所发布的房源 后端接口"""
    login_user = g.user
    try:
        house_list = House.query.filter(House.user_id == login_user.id).all()
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询房屋对象异常")
    if not house_list:
        return jsonify(errno=RET.NODATA, errmsg="该用户未发布房源")

    houses = [house.to_basic_dict() for house in house_list]
    data = {
        "houses": houses
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@register_login_bp.route("/user/avatar", methods=["POST"])
@get_user_info
def update_avatar():
    """修改用户头像 后端接口"""
    # 1.获取参数  [当前登录用户&图片文件]
    login_user = g.user
    avatar = request.files.get("avatar")

    # 2.校验参数
    # 1> 图片数据是否存在
    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    avatar_data = None
    try:
        avatar_data = avatar.read()
    except Exception as err:
        current_app.loggerr.error(err)
        return jsonify(errno=RET.IOERR, errmsg="读取图片数据异常")
    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="图片二进制数据为空")
    # 2> 用户是否登录
    if not login_user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 3.逻辑处理
    # 1> 调用七牛云工具上传图片
    try:
        image_name = pic_store(avatar_data)
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传图片异常")
    if not image_name:
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传图片异常")

    # 2> 修改用户头像路径属性
    login_user.avatar_url = image_name
    try:
        db.session.commit()
    except Exception as err:
        db.session.rollback()
        current_app.logger.error(err)

    # 4.返回值
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + image_name
    }
    return jsonify(errno=RET.OK, errmsg="修改头像成功", data=data)


@api.route("/user/name", methods=["POST"])
@get_user_info
def update_name():
    """修改用户昵称 后端接口  profile.js """
    login_user = g.user
    name = request.json.get("name")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not login_user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    login_user.name = name
    try:
        db.session.commit()
    except Exception as err:
        db.session.rollback()
        current_app.logger.error(err)
        return jsonify(errno=RET.DBERR, errmsg="数据库修改用户昵称属性异常")

    # 实时更新 session中保存的 name
    session["name"] = name

    return jsonify(errno=RET.OK, errmsg="修改昵称成功")

